/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.StringUtil;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 找回密码
 */
public class ReplacePassWordActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ReplacePassWordActivity";
    private EditText et_phone;
    private EditText et_password;
    private EditText et_mobileCode;
    private Button btn_replacePassword;
    private ImageView iv_hide;
    private ImageView iv_show;
    private static final int TIME_COUNTING = 8;
    private static final int TIME_COUNTED = 9;

    int count = 120;//发送短信 等待读秒时间
    Button btn_sendSMSCode;
    private String str_phoneNumber;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


                case TIME_COUNTING:
                    btn_sendSMSCode.setText("" + count);
                    break;
                case TIME_COUNTED:
                    btn_sendSMSCode.setText("重新获取");
                    btn_sendSMSCode.setEnabled(true);
                    break;

            }
            super.handleMessage(msg);
        }
    };
    private Timer timer;
    private TimerTask task;
    private TextView tv_customerService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_replace_pass_word);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);
        btn_sendSMSCode = findViewById(R.id.btn_send_mobile_code);
        et_mobileCode = findViewById(R.id.et_mobile_code);
        // 监听多个输入框

//        et_phone.addTextChangedListener(new TextChange());
//        et_password.addTextChangedListener(new TextChange());
//        et_mobileCode.addTextChangedListener(new TextChange());
        btn_replacePassword = findViewById(R.id.btn_replace_pwd);
        iv_hide = findViewById(R.id.iv_hide);
        iv_show = findViewById(R.id.iv_show);
        tv_customerService = findViewById(R.id.tv_customer_service);
        initPasswordChangeUiListener();
        initTextChangeListener();
        btn_replacePassword.setOnClickListener(this);
        btn_sendSMSCode.setOnClickListener(this);
        tv_customerService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getManualServiceUserInfo();


            }
        });
    }

    private void initPasswordChangeUiListener() {
        iv_hide.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.GONE);
                iv_show.setVisibility(View.VISIBLE);
                et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                // 切换后将EditText光标置于末尾
                et_password.setSelection(et_password.getText().length());

            }

        });
        iv_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.GONE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                // 切换后将EditText光标置于末尾
                et_password.setSelection(et_password.getText().length());
            }

        });
    }

    private void initTextChangeListener() {
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_phone.getCurrentTextColor() == Color.RED) {
                    et_phone.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_password.getCurrentTextColor() == Color.RED) {
                    et_password.setTextColor(getResources().getColor(R.color.text_black));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() > 20) {
                    s.delete(20, 21);
                }
                if (et_password.getText().length() >= 6) {
                    //检测密码强度
                    showToast(et_password, "密码强度：" + StringUtil.validatePassWord(et_password.getText().toString()));
                }
            }
        });

        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (et_password.getText().length() > 0 && et_password.getText().length() < 6) {
                        showToast(btn_sendSMSCode, "密码长度少于6位");
                        et_password.setTextColor(Color.RED);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send_mobile_code:
                sendSMS();

                break;

            case R.id.btn_replace_pwd:
                ReplacePassWord();
                break;
        }
    }

    private void sendSMS() {
        hideSoftKeyboard();
        if (!Utils.isNetworkConnected(this)) {
            showToast_v1(getString(R.string.network_unavailable));
            return;
        }
        btn_sendSMSCode.setEnabled(false);
        str_phoneNumber = et_phone.getText().toString().trim();

        if (TextUtils.isEmpty(str_phoneNumber)) {
            btn_sendSMSCode.setEnabled(true);
            et_phone.setHint("手机号不能为空");
            Utils.editViewValueErrorAnimate(et_phone, this);
            et_phone.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        //不在app 检查手机号格式，因为手机号格式 多变，app 不方便更换 检测的正则 表达式，换成在  服务端检测
        if (!Utils.checkMobileNum(str_phoneNumber)) {
            btn_sendSMSCode.setEnabled(true);
            et_phone.setTextColor(Color.RED);
            Utils.editViewValueErrorAnimate(et_phone, this);
            et_phone.setPadding(Utils.dpToPx(90, this), 0, 0, 0);
            showToast(btn_sendSMSCode, "输入的手机号格式有误");
            return;
        }

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在验证手机号是否注册...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .sendMobileCode_1(str_phoneNumber)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressDialog.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: 发送信息出错" + response.message());
                            showToast(btn_sendSMSCode, getString(R.string.system_busy));
                            btn_sendSMSCode.setEnabled(true);
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "发送信息出错" + result.getMsg());
                            btn_sendSMSCode.setEnabled(true);
                            switch (result.getStatus()) {
                                case Constant.PHONE_NUMBER_INVALID:
                                    showToast("该手机号码尚未注册");
                                    et_phone.setTextColor(Color.RED);
                                    break;

                                case Constant.PHONE_NUMBER_FORMAT_ERROR:
                                    showToast("手机号格式错误");
                                    et_phone.setTextColor(Color.RED);
                                    break;
                                case Constant.SEND_MOBILE_CODE_FAIL_HAVE_NO_COUNT:
                                    // showToast(btn_sendSMSCode, String.format(getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                    ConfirmDialog dialog = new ConfirmDialog(ReplacePassWordActivity.this, "提示", String.format(getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                    dialog.show();
                                    break;
                            }
                            return;
                        }
                        startCount();
                        showToast(btn_sendSMSCode, getString(R.string.SMScode_sended));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressDialog.dismiss();
                        btn_sendSMSCode.setEnabled(true);
                        showToast(btn_sendSMSCode, getString(R.string.system_busy));
                        Log.e(TAG, "发送信息出错" + t.getMessage());
                    }
                });

    }


    private void ReplacePassWord() {
        btn_replacePassword.setEnabled(false);
        hideSoftKeyboard();
        String mobileCode = et_mobileCode.getText().toString().trim();
        String str_newPassWord = et_password.getText().toString().trim();
        str_phoneNumber = et_phone.getText().toString().trim();

        if (TextUtils.isEmpty(str_phoneNumber)) {
            btn_replacePassword.setEnabled(true);
            et_phone.setHint("手机号不能为空");
            Utils.editViewValueErrorAnimate(et_phone, this);
            et_phone.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (!Utils.checkMobileNum(str_phoneNumber)) {
            btn_replacePassword.setEnabled(true);
            et_phone.setTextColor(Color.RED);
            Utils.editViewValueErrorAnimate(et_phone, this);
            et_phone.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            showToast(btn_replacePassword, getString(R.string.phone_number_type_error));
            return;
        }


        if (TextUtils.isEmpty(mobileCode)) {
            btn_replacePassword.setEnabled(true);
            et_mobileCode.setHint("验证码不能为空");
            Utils.editViewValueErrorAnimate(et_mobileCode, this);
            et_mobileCode.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (TextUtils.isEmpty(str_newPassWord)) {
            btn_replacePassword.setEnabled(true);
            et_password.setHint("密码不能为空");
            Utils.editViewValueErrorAnimate(et_password, this);
            et_password.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }

        if (str_newPassWord.length() < 6) {
            btn_replacePassword.setEnabled(true);
            et_password.setTextColor(Color.RED);
            showToast(btn_replacePassword, "密码长度不足6位");
            Utils.editViewValueErrorAnimate(et_password, this);
            et_password.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }


        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage("正在保存新密码...");
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.show();
        Map<String, Object> info = new HashMap<>();
        info.put("phoneNumber", str_phoneNumber);
        info.put("mobileCode", mobileCode);
        info.put("password", str_newPassWord);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .modifyPassword(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        pd.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            btn_replacePassword.setEnabled(true);
                            Log.e(TAG, "onResponse: 保存新密码出错" + response.message());
                            showToast(btn_replacePassword, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            btn_replacePassword.setEnabled(true);
                            Log.e(TAG, "保存新密码出错" + result.getMsg());
                            switch (result.getStatus()) {

                                case Constant.PHONE_NUMBER_INVALID:
                                    showToast(btn_replacePassword, "该号码尚未使用");
                                    return;
                                case Constant.MOBILE_CODE_ERROR:
                                    showToast(btn_replacePassword, getString(R.string.mobile_code_error));
                                    return;
                                case Constant.MOBILE_CODE_EXPIRE:
                                    showToast(btn_replacePassword, getString(R.string.mobile_code_expire));
                                    return;
                                case Constant.MOBILE_CODE_USED:
                                    showToast(btn_replacePassword, getString(R.string.mobile_code_used));
                                    return;

                            }
                        }
                        btn_replacePassword.setEnabled(false);
                        showToast(btn_replacePassword, "密码重置完成");
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 1500);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_replacePassword.setEnabled(true);
                        pd.dismiss();
                        Log.e(TAG, "onResponse: 保存新密码出错" + t.getMessage());
                        showToast(btn_replacePassword, getString(R.string.system_busy));
                    }
                });


    }


    public void startCount() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                if (count > 0) {
                    handler.sendEmptyMessage(TIME_COUNTING);
                    count--;
                } else {
                    timer.cancel();
                    count = 60;
                    handler.sendEmptyMessage(TIME_COUNTED);

                }
            }
        };
        timer.schedule(task, 0, 1000);
    }

    void getManualServiceUserInfo() {
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        startActivity(new Intent(ReplacePassWordActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, manualUser));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }

}
